class Task
  constructor: (task_id) ->
    if task_id
      $.ajaxSetup beforeSend: (xhr) ->
        xhr.setRequestHeader "X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content")
      $.ajax
        url: "s/#{task_id}"
        type: "GET"
        async: true
        success: (retval) =>
          if retval.error
            $("BODY").f_popup content: retval.msg.content
          else
            console.log retval
            _task = retval.value
            @_id             = task_id
            @keyword         = _task.keyword
            @current_page    = _task.current_page
            @detail          = _task.detail
            @sorttype        = _task.sorttype
            @msgtype         = _task.msgtype
            @starttime       = _task.starttime
            @endtime         = _task.endtime
            @longitue        = _task.longitue
            @latitude        = _task.latitude
            @radius          = _task.radius
            @searchtime      = _task.searchtime
            @province        = _task.province
            @city            = _task.city
            @is_filter       = _task.is_filter
            @search_type     = _task.search_type
            @total_num       = _task.total_num
            @is_filter       = false
            @_pages          = _task.pages
            @comment_data    = _task.comment_data
            @comment_data = {tweets:[],comment:""}
            @selected_count  = 0
          this.render()
          this.save()
        error: (retval) ->
          this.new()
    else
      this.new()
    this

  page: (_pno) ->
    this._pages[_pno - 1]

  rendered_page: (_pno)->
    _rp = []
    for page in this._pages
      _rp.push page if page.rendered
    if _pno
      _rp(_pno)
    else
      _rp

  add_comment_tweet: (tweet) ->
    push_flag = true
    for _t in @comment_data.tweets
      push_flag = false if _t.wid == tweet.wid || (_t.uid == tweet.uid && tweet.uid != "" )
    if push_flag
      @comment_data.tweets.push(tweet)
      @selected_count += 1
  remove_comment_tweet: (tweet) ->
    _tweets = []
    for _t in @comment_data.tweets
      _tweets.push _t unless _t.wid == tweet.wid ||(_t.uid == tweet.uid && _t.uid.toString() != 'undefined')
    @selected_count = _tweets.length
    @comment_data.tweets = _tweets


  render: () ->
    console.log "开始渲染"
    $(".search input").val(@keyword)
    $("#edit-txt").val(@comment_data.comment)
    item_html = ""
    pindex = this.rendered_page().length
    $("#choosePage").show() if this._pages.length > 0

    for _page in this._pages
      index   = 0
      if _page.rendered
        continue
      else
        for tweet in _page.tweets
          item_html = "
            <li id=\"tweet_#{tweet.id}\" data=\"#{'tweet-'+ (pindex+1) + '-' + index + '-' + tweet.id + '-' + tweet.user.id }\" class=\"#{if tweet.commented then 'unable active' else 'available'}\" style=#{ if (index % 2 == 0) then '"margin:0px"' else ''}>
              <span class=\"microblog-panel-top\">
                #{if tweet.commented then "<span class=\"send-succeed\">#{tweet.commented}</span>" else '<input type="checkbox">'}
                <span class=\"header\">
                  <img src=\"#{tweet.user.profile_image_url}\" alt=\"\">
                </span>
                <span class=\"username\"><strong>#{tweet.user.name}</strong></span>
                <span class=\"gender\">#{tweet.user.gender}</span>
                <span class=\"location\">#{tweet.user.location}</span>
              </span>
              <span class=\"microblog-panel-bottom\">
                <span class=\"microblog-content\">
                  <span class=\"microblog-text\">#{$.matchStrs($.subStr(tweet.text, 90), this.keyword)}</span>
                  <span class=\"date-time\">#{tweet.created_at}</span>
                </span>
                #{if tweet.bmiddle_pic then "<span class=\"img\"><img src=\"#{tweet.bmiddle_pic}\" alt=\"\">" else ''}
                </span>
              </span>
            </li>
          "
          $(".microblog-list").append item_html
          index += 1
        _page.rendered = true
        pindex += 1
    $.setWaitState false
    $(".check-all input").prop 'checked', false


  search: (options)->
    options           ||= {}
    options.success   ||= (retval)->{}
    options.error     ||= (retval)->{}
    options.complete  ||= (retval)->{}

    $.ajaxSetup beforeSend: (xhr) ->
      xhr.setRequestHeader "X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content")
    $.ajax
      url: "s/search"
      type: "POST"
      async: true
      data:
        task            : this._id
        keyword         : this.keyword
        current_page    : options.current_page || this.current_page || this._pages.length ||1
        detail          : this.detail
        sorttype        : this.sorttype
        msgtype         : this.msgtype
        starttime       : this.starttime
        endtime         : this.endtime
        longitue        : this.longitue
        latitude        : this.latitude
        radius          : this.radius
        searchtime      : this.searchtime
        province        : this.province
        city            : this.city
        is_filter       : this.is_filter
        search_type     : this.search_type
        is_filter       : this.is_filter

      success: (retval) =>
        if retval.error
          $("BODY").f_popup content: retval.msg.content
        else
          console.log retval
          this._id = retval.value.task
          this.current_page = retval.value.current_page
          this.total_num    = retval.value.total_num
          this._pages.push
            tweets: retval.value.tweets
            rendered: false
          this.render()
          this.save()
          options.success(retval)
      error: (retval) ->
        console.log retval
        options.error(retval)
        $("BODY").f_popup content: "系统繁忙，请稍后重试！"
      complete: (retval) ->
        @is_filter = false
        options.complete(retval)

  next: ->
    this.search
      current_page: this.current_page + 1

  filter: ->
    @current_page = 1
    @starttime    = $("#starttime").val() + "-" + $("#starthour").find("span").html() unless $("#starttime").val() is ""
    @endtime      = $("#endtime").val() + "-" + $("#endhour").find("span").html() unless $("#starttime").val() is ""
    @province     = $("#province").find("span").attr("value")
    @city         = $("#city").find("span").attr("value")
    @_pages       = []
    @comment_data = {tweets:[],comment:""}
    @is_filter    = true
    this.save()
    this.search()

  create_comment: () ->
    _rfc = this.ready_for_comment()
    $.ajax
      url: "s"
      type: "POST"
      data:
        comment: _rfc.comment
        tweets:  _rfc.tweets
        task:    @_id

      success: (retval) ->
        $.waitState false, "推送", $(".push-btn")
        console.log "success comment_weibos"
        $("BODY").f_popup content: "您已成功发送！"
        for tweet in _rfc.tweets
          tweet.commented = true
          $("#tweet_#{tweet.wid}").removeClass("available").addClass("unable active").find(".microblog-panel-top input").replaceWith('<span class="send-succeed">正在发送</span>')
        $(".chooseNum").html 0
      error: (retval) ->
        $("BODY").f_popup content: "系统繁忙，请稍后重试！"
        $.waitState false, "推送", $(".push-btn")
        console.log "error comment_weibos"
        console.log retval
  # #################################

  ready_for_comment: =>
    _tweets = new Array
    for _t in @comment_data.tweets
      _tweets.push _t unless _t.commented
    {
      tweets: _tweets
      comment: $("#edit-txt").val()
    }

  new:()=>
    @_id             = null
    @current_page    = 1
    @keyword         = null
    @detail          = null
    @sorttype        = null
    @msgtype         = null
    @starttime       = null
    @endtime         = null
    @longitue        = null
    @latitude        = null
    @radius          = null
    @searchtime      = null
    @province        = null
    @city            = null
    @is_filter       = false
    @search_type     = $(".engine-toggle").attr('data')
    @total_num       = null
    @_pages          = []
    @comment_data = {tweets:[],comment:""}
    this.save()
    this

  save: () =>
    $.cookie("task_id", this._id)

  window.Task = Task
